<template>
    <div>
        <el-dialog v-model="props.dialogVisible" :title="props.status" width="45%" :before-close="handleClose" :close-on-click-modal="false"
        :close-on-press-escape="false">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
                status-icon> 
                <el-form-item label="视频名称" prop="class_name"> 
                    <el-input v-model="ruleForm.class_name" />
                </el-form-item>
                
                <el-form-item label="配套讲义" prop="pdf">
                    <div>
                        <div>{{pdfName}}</div>
                        <el-progress style="width: 100px;" :percentage="progressPercent"/>
                    </div>
                    <el-upload ref="uploadRef" class="upload-demo" action="#" :http-request="uploadPdf"
                        :show-file-list="false">
                        <template #trigger>
                            <el-button type="primary">重新上传</el-button>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item label="讲师姓名" prop="name">
                    <el-select v-model="ruleForm.name" placeholder="请选择讲师姓名" remote-show-suffix @focus="remoteMethod"
                        @change="change" clearable style="width: 220px;">
                        <el-option v-for="item in options" :key="item.appId" :label="item.name + '-' + item.phone"
                            :value="item.name + '-' + item.phone" />
                    </el-select>
                </el-form-item>
                <el-form-item label="上传端口" prop="upload_port">  
                    <el-input v-model="ruleForm.upload_port" :disabled="true" />
                </el-form-item>
                <el-form-item label="上传人" prop="upload_name">  
                    <el-input v-model="ruleForm.upload_name" :disabled="true" />
                </el-form-item>
                <el-form-item label="课时标签" prop="identity">  
                    <el-input v-model="ruleForm.identity" :disabled="true" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closeDiglog">取消</el-button>
                    <el-button type="primary" @click="submit">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import type { FormInstance, FormRules, UploadRequestOptions } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { uploadFile, searchTeacher, uploadFdf, sumbitLesson } from '../api/uploadVideo'
const props = defineProps(['dialogVisible', 'status', 'courseInfo'])
import { useRouter } from 'vue-router';
const router = useRouter();
interface RuleForm {
    name: string
    phone: string,
    video: any,
    pdf: any,
    class_name: any,
    class_time: any,
    class_link: any,
    class_number: any,
    upload_port: any,
    upload_name: any,
    identity: any
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    name: '',
    phone: "",
    video: "",
    pdf: '',
    class_name: "",
    class_time: "",
    class_link: "",
    class_number: '',
    upload_port: '',
    upload_name: '',
    identity: ''
})
watch(() => props.dialogVisible, (newVal, oldVal) => {
    if (newVal) {
        ruleForm.class_name = props.courseInfo.class_name
        ruleForm.phone = props.courseInfo.teacher_phone
        ruleForm.upload_port = props.courseInfo.upload_port
        ruleForm.upload_name = props.courseInfo.upload_name
        ruleForm.identity = props.courseInfo.identity
        searchTeacher({ name: '', phone: props.courseInfo.teacher_phone }).then(res => {
            if (res) {
                ruleForm.name = res.list[0].name + '-' + res.list[0].phone
            }
        })
    }
})

const validateclassname = (rule: any, value: any, callback: any) => {
    console.log(value,'课时名称')
  if (value === '') {
    callback(new Error('请输入课时名称'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '请输入讲师姓名', trigger: 'blur' }
    ],
    phone: [{
        required: true, message: '请输入讲师电话', trigger: 'blur'
    }],
    class_name: [
        {
            validator: validateclassname, trigger: 'blur'
        }
    ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}
//搜索讲师姓名
const options = ref([])
const remoteMethod = () => {
    searchTeacher({ name: '', phone: '' }).then(res => {
        if (res) {
            options.value = res.list
        }
    })
}
//选中值发生变化时触发
const change = (e: any) => {
    console.log(e, '下拉选项')
    ruleForm.phone = e
}
const handleClose = (done: () => void) => {
    closeDiglog()
    done()
}
const emits = defineEmits(['closeDiglog'])
const closeDiglog = () => {
    emits('closeDiglog')
}
const beforeUpload = (rawFile: any) => {
    if (rawFile.file.type !== 'video/mp4' && rawFile.file.type !== 'video/mov') {
        ElMessage.error('请选择文件格式为mp4、mov')
        return false
    }
    if ((rawFile.file.size / (1024 * 1024 * 1024)) > 1) {
        ElMessage.error('上传视频不超过1GB')
        return false
    }
    ruleForm.class_name = rawFile.file.name.split('.mp4')[0]
    var url = URL.createObjectURL(rawFile.file);
    var audioElement = new Audio(url);
    var duration;
    audioElement.addEventListener("loadedmetadata", function (_event) {
        duration = parseInt(audioElement.duration.toString());
        ruleForm.class_time = duration
    });
    return true
}
//上传讲义
const progressPercent = ref(0)
const pdfName = ref('')
const pdfFile: any = ref(false)
const uploadPdf = (options: UploadRequestOptions) => {
    let form = new FormData()
    pdfName.value = options.file.name
    form.append('file', options.file)
    form.append('class_number', props.courseInfo.class_number)
    uploadFdf(form).then(res => {
        progressPercent.value = 100
        if (res.code === '200') {
            pdfFile.value = true
            ElMessage.success(res.msg)
        }
    })
}
//上传文件
const videoFile: any = ref(false)
const uploadRquest = (options: UploadRequestOptions) => {
    if (beforeUpload(options)) {
        let data: any = localStorage.getItem('token')
        let { teacher_name, phone } = JSON.parse(data)
        let form = new FormData()
        form.append('video', options.file)
        form.append('updateUserName', teacher_name)
        form.append('upload_phone', phone)
        form.append('class_name', ruleForm.class_name)
        uploadFile(form).then((res: any) => {
            if (res.code === '200') {
                ElMessage.success('视频上传完成')
                videoFile.value = true
                // ruleForm.class_link = res.data[0].url
                ruleForm.class_number = res.data[0].class_number
            }
        })
    }
}
//修改提交
const submit = () => {
    let that:any = this 
    let [name, phone] = ruleForm.name.split('-')
    let class_link = undefined
    searchTeacher({ name: '', phone }).then(res => {
        if (res) {
            class_link = res.list[0]?.picture[0]?.url
            let params = {
                class_number: props.courseInfo.class_number,
                class_teacher: name,
                class_time: props.courseInfo.class_time,
                teacher_phone: phone,
                picture: class_link,
                class_name:ruleForm.class_name
            }
            sumbitLesson(params).then(res => {
                if (res.code === '200') {
                    ruleForm.name =''
                    ElMessage.success('提交成功')
                    closeDiglog()
                    router.push({ path: "/course" });
                    that.$emit('getCourse') //更新编辑后的课程列表
                }else{ 
                    ElMessage.error(res.msg) 
                    closeDiglog()  
                    router.push({ path: "/course" });
                    that.$emit('getCourse') //更新编辑后的课程列表
                }
            })
        }
    })
}
</script>

<style scoped></style>